﻿using LiteBlog.Components.Contracts;
using LiteBlog.Controllers.Contracts;
using LiteBlog.Controllers.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace LiteBlog.Controllers
{
    public class SkinController : BaseController, ISkinController
    {
        public SkinController(ISettingsComp settingsComp, ICacheComp cacheComp) : base(settingsComp, cacheComp) { }

        public ActionResult Blog()
        {
            var variables = SkinHelper.GetVariablesForBlog(SkinHelper.GetSkin());
            var totalBytes = GetBytes("common.dynamic", "blog", variables);
            return File(totalBytes, "text/css");
        }

        public ActionResult Admin()
        {
            var variables = SkinHelper.GetVariablesForAdmin(SkinHelper.GetSkin());
            var totalBytes = GetBytes("common.dynamic", "admin", variables);
            return File(totalBytes, "text/css");
        }

        [HttpPost]
        public ActionResult Change(string id)
        {
            if (Request != null && Request.Cookies != null)
            {
                var cookie = Request.Cookies["Skin"];
                if (cookie == null)
                {
                    cookie = new System.Web.HttpCookie("Skin", id);
                    cookie.Expires = DateTime.Now.AddMonths(1);
                    if (Response != null && Response.Cookies != null)
                        Response.Cookies.Add(cookie);
                }
                else
                {
                    cookie.Value = id;
                    if (Response != null)
                        Response.SetCookie(cookie);
                }
            }

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        private byte[] GetBytes(string commonStyleFile, string areaStyleFile, List<KeyValuePair<string, string>> variables)
        {
            string commonStyle = GetString(commonStyleFile, variables);
            string areaStyle = GetString(areaStyleFile, variables);
            string style = string.Concat(commonStyle, areaStyle);
            return Encoding.UTF8.GetBytes(style);
        }

        private string GetString(string styleFile, List<KeyValuePair<string, string>> variables)
        {
            string style = string.Empty;
            if (Server != null)
            {
                var file = Server.MapPath(string.Format("~/Content/{0}.css", styleFile));
                style = System.IO.File.ReadAllText(file);

                foreach (var variable in variables)
                {
                    style = style.Replace(variable.Key, variable.Value);
                }
            }
            return style;
        }

        public void ResolveComponents()
        {
            
        }
    }
}
